package com.gitee.ricesugar.mall.servlets;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.ricesugar.mall.model.POJO.DTO.ProductDTO;
import com.gitee.ricesugar.mall.model.Service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;

@WebServlet(name = "GetProductServlet", value = "/getProduct")
public class GetProductServlet extends HttpServlet {

    private ProductService productService;

    @Override
    public void init() throws ServletException {
        try {
            productService = new ProductService();
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ProductDTO product = null;
        Writer out = response.getWriter();

        String id = request.getParameter("id");

        try {
            product = productService.getProduct(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(product);

        out.write(json);
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
